package xGRUx.MCdirGlztab.Xml;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import xGRUx.MCdirGlztab.R;
import xGRUx.MCdirGlztab.Views.StoryItem;

public class XPathHelper
{
	private XPath m_Xpath;
	private InputSource m_ISrc;
	
	public XPathHelper(InputStream istrm) {
		this.m_Xpath = XPathFactory.newInstance().newXPath();
		this.m_ISrc = new InputSource(istrm);
	}
	
	public String getString(String xpath) {
		try
		{
			Node node = (Node) this.m_Xpath.evaluate(xpath, this.m_ISrc, XPathConstants.NODE);
			return node.getTextContent();
		} catch (XPathExpressionException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}
	
	public List<StoryItem> getStoryItems(String xpath) {
		try
		{
			NodeList nodes = (NodeList) this.m_Xpath.evaluate(xpath, this.m_ISrc, XPathConstants.NODESET);
			
			List<StoryItem> list = new ArrayList<StoryItem>();
			
			for(int i = 0; i < nodes.getLength(); i++) {
				
				Node node = nodes.item(i);
				
				StoryItem item = createItem(
						this.m_Xpath.evaluate("title", node), 
						this.m_Xpath.evaluate("time", node), 
						this.m_Xpath.evaluate("loc", node), 
						this.m_Xpath.evaluate("content", node), 
						this.m_Xpath.evaluate("uid", node));
				list.add(item);
			}
			
			return list;
		} catch (XPathExpressionException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private StoryItem createItem(String title, String time, 
			String loc, String content, String uid){
		StoryItem o = new StoryItem();
		o.setTitle(title);
		o.setTimeToGo(time);
		o.setImgSrc(R.drawable.unread);
		o.setContents(content);
		o.setGoLocation(loc);
		o.setUID(uid);
		return o;
	}
}
